#!/bin/bash
# 获取本机 IP 地址的辅助脚本

echo "正在获取本机 IP 地址..."
echo ""

# Mac/Linux
if [[ "$OSTYPE" == "darwin"* ]] || [[ "$OSTYPE" == "linux-gnu"* ]]; then
    # 尝试获取 en0 (Mac) 或主要网络接口的 IP
    if command -v ipconfig &> /dev/null; then
        # Mac
        IP=$(ipconfig getifaddr en0 2>/dev/null || ipconfig getifaddr en1 2>/dev/null)
        if [ -z "$IP" ]; then
            IP=$(ifconfig | grep "inet " | grep -v 127.0.0.1 | awk '{print $2}' | head -1)
        fi
    else
        # Linux
        IP=$(hostname -I | awk '{print $1}' 2>/dev/null)
        if [ -z "$IP" ]; then
            IP=$(ip route get 8.8.8.8 2>/dev/null | awk '{print $7; exit}')
        fi
    fi
# Windows (Git Bash)
elif [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "cygwin" ]]; then
    IP=$(ipconfig | grep "IPv4" | head -1 | awk '{print $NF}')
fi

if [ -z "$IP" ]; then
    echo "❌ 无法自动获取 IP 地址"
    echo ""
    echo "请手动执行以下命令获取 IP："
    echo "  Mac: ipconfig getifaddr en0"
    echo "  Linux: hostname -I"
    echo "  Windows: ipconfig (查找 IPv4 地址)"
    exit 1
fi

echo "✅ 找到本机 IP 地址: $IP"
echo ""
echo "使用以下命令运行 Flutter 应用："
echo ""
echo "  flutter run --dart-define=API_BASE_URL=http://$IP"
echo ""
echo "或者只设置 IP（会自动添加 http://）："
echo ""
echo "  flutter run --dart-define=API_BASE_URL=$IP"
echo ""
